<template>
    <el-dialog custom-class="my-dialog" :title="dialogTitle" :visible="isDetailVisible" width="758px">
        <el-form status-icon ref="refruleForm" :rules="rules" :model="ruleForm" label-width="100px" size="small">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="书签名称" prop="title">
                        <el-input v-model="ruleForm.title" placeholder="请输入书签名称"></el-input>
                    </el-form-item>
                </el-col>
                <!--<el-col :span="12">-->
                <!--    <el-form-item label="书签目录" prop="path">-->
                <!--        <div id="select">-->
                <!--            <ElementTreeSelect />-->
                <!--        </div>-->
                <!--    </el-form-item>-->
                <!--</el-col>-->
                <el-col :span="12">
                    <el-form-item label="书签目录" prop="path">
                        <div id="select">
                            <SelectTree
                                :clearable="isClearable"
                                :accordion="isAccordion"
                                :clickable="attachParams.level !== 0"
                                :props="selectTreeProps"
                                :options="listTree"
                                :value="valueId"
                                @refreshPid="refreshPid($event)"/>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="类型" prop="type">
                        <!--<el-input v-model="ruleForm.type" placeholder="请输入书签类型"></el-input>-->
                        <el-select v-model="ruleForm.type" placeholder="请选择书签类别" :disabled="attachParams.flag === 'edit' || attachParams.level === 0">
                            <el-option label="目录" :value="0"></el-option>
                            <el-option label="书签" :value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="LOGO地址" prop="logo">
                        <el-input v-model="ruleForm.logo" placeholder="请输入LOGO地址"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="访问地址" prop="url">
                        <el-input v-model="ruleForm.url" placeholder="请输入访问绝对地址" :disabled="ruleForm.type === 0"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="书签描述" prop="desc">
                        <el-input type="textarea" clearable placeholder="请输入书签描述" v-model="ruleForm.desc"/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeViews" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="small">确 定</el-button>
      </span>
        </template>
    </el-dialog>
</template>
<script>
import {reactive, ref, toRefs} from '@vue/reactivity'
import {nextTick, watch} from '@vue/runtime-core'
import {ElMessage} from 'element-plus'
import BookmarkApi from '../Api/bookmark'
// import SelectTree from "./treeSelect.vue"
import SelectTree from "./My-Tree-Select"
import CacheStore from '../utils/cacheStore'
import Tools from '../utils/tools'

const value = ref()

export default {
    name: "dialog",
    components: {SelectTree},
    model: {
        value: 'isDetailVisible',
        events: 'closeViews'
    },
    // props 拿到父组件传来的值
    props: {
        isDetailVisible: {
            type: Boolean,
            default: false
        },
        detail: {
            type: Object,
            default: () => {
            }
        }
    },
    setup(props, context) {
        console.log('dialog-setup->props:')
        console.log(props)
        // 表单数据
        const form = reactive({
            ruleForm: {
                title: '',
                pid: '',
                type: '',
                desc: '',
                url: '',
                logo: ''
            },
            attachParams: {
                level: 0,
                flag: ''
            },
            dialogTitle: ''
        })

        // 定义校验规则 表单代码中必须以 :rules 接收
        const rules = {
            title: [{required: true, message: '请输入书签名称', trigger: 'blur'}],
            type: [{required: true, message: '请选择书签类别', trigger: 'change'}]
        }
        const refruleForm = ref(null)

        /**
         * 书签编辑/新增，是否必填规则
         * 书签名称：必填
         * 书签目录：顶级目录不可编辑
         * 书签类型：编辑时，直接锁定不可更改。新增时，顶级目录锁定为目录
         * logo_url：可选
         * url：当类型为目录时，不可编辑
         * desc：可选
         */
        const submitForm = () => {
            /**
             * 这里先搞个丐版的，不考虑类型修改，不支持切换目录，也就是只能改书签内容，不能书签树改位置
             */
            refruleForm.value.validate((valid) => {
                if (valid) {
                    // 当前书签类别，来自App-json.vue 书签编辑方法
                    let myDetail = {...props.detail}
                    // 表单提交内容，书签编辑内容/书签新增内容
                    let formData = {...form.ruleForm}
                    console.log(formData)

                    // 丐版不考虑书签目录切换，这里就不对书签类别进行比较了

                    if (props.detail.flag === 'edit') {
                        // 编辑
                        let query = {...formData}
                        console.log(query)
                        BookmarkApi.editBookmark(query).then(result => {
                            ElMessage.success('编辑成功')
                            closeViews()
                            // 这里如果pid有变动，则进行重新刷新
                            if (result.message === 'refresh') {
                                context.emit('refresh', 'refresh')
                            } else {
                                context.emit('refresh', 'edit', result.body)
                            }
                        })
                    } else {
                        // 新增
                        let userInfo = Tools.jsonParser(CacheStore.getCookie("userInfo"));
                        if (typeof userInfo === undefined || userInfo === '') {
                            ElMessage.error('找不到userInfo')
                        } else {
                            let query = Object.assign(
                                {
                                    ...formData
                                },
                                {
                                    userid: userInfo.userid
                                })
                            console.log("add->query:")
                            console.log(query)
                            BookmarkApi.addBookmark(query).then(result => {
                                ElMessage.success('添加成功')
                                closeViews()
                                // 添加成功会返回添加的书签，这里直接取[0]了
                                context.emit('refresh', myDetail.pid !== '0' ? 'add' : 'addTop', result.body)
                            }).catch(err => {
                                ElMessage.error(err.message)
                            })
                        }
                    }
                }
            })
        }

        // treeSelect组件数据
        const selectTreeData = reactive({
            isClearable: true,
            isAccordion: true,
            isClickable: false,
            // 目录树中节点id，传入的为pid
            valueId: '',
            selectTreeProps: {
                value: 'id',
                label: 'title',
                children: 'children'
            },
            listTree: {...props.detail}.treeData
        })

        /**
         * 更新传入目录树组件数据
         * 包括选中当前目录即pid
         * 以及目录树数据，为了确保实时这个需要每次更新
         * 数据只管传，其他判断目录树组件会进行
         */
        const refreshSelectTreeData = () => {
            let myDetail = {...props.detail}
            selectTreeData.valueId = myDetail.pid
            selectTreeData.listTree = myDetail.treeData
        }

        // 关闭弹窗
        const closeViews = () => {
            refruleForm.value.resetFields()
            context.emit('closeViews', false)
        }

        /*
            监听detail
            编辑、新增操作开启编辑页面后，监听传入detail，有变化则更新
            编辑页面：更新相应数据
            目录书组件：更新pid与目录树数据
         */
        watch(
            () => props.detail,
            (v) => {
                if (v) {
                    nextTick(() => {
                        // 修改编辑页面数据
                        form.ruleForm = {...props.detail}
                        form.attachParams = {...props.detail.attachParams}
                        form.attachParams.flag = props.detail.flag
                        if (props.detail.flag === 'edit') {
                            form.dialogTitle = '编辑书签'
                        } else {
                            form.dialogTitle = '新增书签'
                        }
                        // 修改目录树组件参数
                        refreshSelectTreeData()
                    })
                }
            },
            {deep: true}
        )
        return {
            ...toRefs(form),
            ...toRefs(selectTreeData),
            closeViews,
            submitForm,
            refruleForm,
            rules
        }
    },
    methods: {
        // 目录树组件中，选择了目录或清空，需要回传到该方法进行更新
        refreshPid(value) {
            this.valueId = value;
            this.ruleForm.pid = value;
            console.log("refreshPid->valueId:")
            console.log(this.valueId)
            console.log("refreshPid->ruleForm:")
            console.log(this.ruleForm)
        }
    }
}
</script>
<style scoped lang="scss">
.my-dialog {
    background: red;
}

.my-dialog /deep/ .el-dialog__header {
    border-bottom: 1px solid #eee !important;
}

.my-dialog /deep/ .el-dialog__title {
    font-size: 16px;
    color: #e03b5d;
}
</style>
